package com.cqyanyu.yanyu;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;

import org.xutils.x;

/**
 * MEAT_DATA 配置数据
 * Created by cheng on 2016/6/23.
 */
public class XMeatData {
    public String HOST_URL = null;
    public static XMeatData xMeatData;

    public XMeatData() {
        ApplicationInfo appInfo = null;
        try {
            appInfo = x.app().getPackageManager()
                    .getApplicationInfo(x.app().getPackageName(),
                            PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            Logger.e("获取HOST_URL错误", e);
        }
        if (appInfo == null) {
            return;
        }
//获取服务器地址
        int host_type = appInfo.metaData.getInt("HOST_TYPE", 0);
        if (BuildConfig.DEBUG) {
            switch (host_type) {
                case 1:
                    HOST_URL = appInfo.metaData.getString("HOST_TEST_URL");
                    break;
                case 2:
                    HOST_URL = appInfo.metaData.getString("HOST_RAP_URL");
                    break;
                default:
                    HOST_URL = appInfo.metaData.getString("HOST_URL");
            }
        } else {
            HOST_URL = appInfo.metaData.getString("HOST_URL");
        }


    }

    public final static XMeatData getInstance() {
        if (xMeatData == null) {
            xMeatData = new XMeatData();
        }
        return xMeatData;
    }


    /**
     * 获取服务器地址
     *
     * @return
     */
    public final static String getHostUrl() {
        Logger.d("服务器地址:" + getInstance().HOST_URL);
        return getInstance().HOST_URL;
    }

    /**
     * 判断地址是否完整，获取完整地址
     *
     * @param url
     * @return
     */
    public final static String getUrlAll(String url) {
        if (url == null || url.equals("")) {
            url = "";
        } else {
            String url1 = url.toLowerCase();
            if (!url1.startsWith("http://") && !url1.startsWith("https://")) {
                if (url.length() > 1 && url.substring(0, 1).equals("/")) {
                    url = url.substring(1, url.length());
                }
                url = XMeatData.getHostUrl() + url;
            }
        }
        return url;
    }

    /**
     * 如果是oss url则拼接
     *
     * @param url
     * @return
     */
    public final static String getUrlOSSStyle(String url, String ossStyle) {
        if (!TextUtils.isEmpty(url) && url.startsWith("http://oss.huomantech")) {
            return url + ossStyle;
        } else {
            return url;
        }
    }
}

